import React from "react";
import GoBack from "@/components/TheGoBack";
import TheUpload from "@/components/TheUpload";
import {CloseCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Form, Input, Space, Radio, InputNumber, DatePicker, Select, Modal} from "antd";
import _ from 'lodash'
import {apiAppConfigCarouselAdd, apiAppConfigCarouselEdit, apiAppConfigCarouselView} from '@/request/app/appScreenAD'
import {apiActivityLinkList} from "@/request/h5"
import List from "../../../settings/shuffling/component/carousellist";
import moment from 'moment';

const {Option} = Select
const {RangePicker} = DatePicker;

class Edit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            showUpFile: true,
            fileList: [],
            radioValue: '0',
            typeTitle: '',
            visible: false,
            btnLoading: false,
            AdID: '',
            fileType: 'image',
            maxSize: 10,
            initialValues: {
                configCarouselShowType: 0,
                configCarouselUri: "",
                configCarouselType: "0"
            },
            configCarouselUri: '',
            activeList: [],
            arr: [],
        };
    }

    async componentDidMount() {
        this.getActiveList()
        const {id} = this.props.match.params
        if (id != 0) {
            await this.getData(id)
        }
        this.setState({
            AdID: id,
            showUpFile: 'true',
        })
        // console.log(id)
    }

    // 外链地址下拉内容
    async getActiveList() {
        await apiActivityLinkList().then(res => {
            console.log(res);
            if (res.code === 0) {
                this.setState({
                    activeList: res.data
                })
            }
        })
    }

    getData = async (e) => {
        let res = await apiAppConfigCarouselView({
            configCarouselId: e,
        })
        if (res.code === 0 && res.data) {
            if (res.data.configCarouselType !== '1') {
                if (res.data.configCarouselUri !== '') {
                    const carouselUri = JSON.parse(res.data.configCarouselUri)
                    this.setState({
                        configCarouselUri: res.data.configCarouselUri
                    })

                    // switch (res.data.configCarouselType) {
                    //     case '2':
                    //         res.data.configCarouselUri = carouselUri.storeName
                    //         break;
                    //     case '3':
                    //         res.data.configCarouselUri = carouselUri.goodsName + carouselUri.storeName
                    //         break;
                    //     case '4':
                    //         res.data.configCarouselUri = carouselUri.storeName
                    //         break;
                    //     case '5':
                    //         res.data.configCarouselUri = carouselUri.productName + carouselUri.storeName
                    //         break;
                    //     case '6':
                    //         res.data.configCarouselUri = carouselUri.serviceName + carouselUri.storeName
                    //         break;
                    //     case '7':
                    //         res.data.configCarouselUri = ''
                    //         break;
                    //     case '8':
                    //         res.data.configCarouselUri = ''
                    //         break;
                    //     case '9':
                    //         res.data.configCarouselUri = carouselUri.serviceClassifyName
                    //         break;
                    //     case '10':
                    //         res.data.configCarouselUri = ''
                    //         break;
                    //     case '11':
                    //         res.data.configCarouselUri = ''
                    //         break;
                    //     case '12':
                    //         res.data.configCarouselUri = ''
                    //         break;
                    //     default:
                    //         break;
                    // }
                }
            } else {
                let users = []
                let url = []
                if (res.data.configCarouselUri.indexOf('?') != '-1') {
                    url = res.data.configCarouselUri.split('?')
                    res.data.configCarouselUri = url[0]
                    users = (url[1].split('&'))
                    let str = ''
                    users.map((item) => {
                        str = item.split('=')
                        this.state.arr.push({
                            key: str[0],
                            value: str[1]
                        })
                    })
                } else {
                    res.data.configCarouselUri = res.data.configCarouselUri.trim()
                }

                // value.configCarouselUri= JSON.stringify(value.configCarouselUri)
            }
            let fileList = [
                {
                    uid: '-1',
                    name: 'image.png',
                    status: 'done',
                    url: res.data.configCarouselFilez,
                },
            ]
            this.setState({
                fileList: [...fileList],
                radioValue: res.data.configCarouselType,
                configCarouselUri: res.data.configCarouselUri,
            }, () => {
                this.formRef.setFieldsValue(
                    {
                        ...res.data,
                        time: [
                            moment(res.data.startTime, 'YYYY-MM-DD HH:mm:ss'),
                            moment(res.data.endTime, 'YYYY-MM-DD HH:mm:ss'),
                        ]
                    })
            })
        }
    }
    //form表单确定事件
    onFinish = async (values) => {
        this.setState({btnLoading: true})
        if (this.state.radioValue != "1") {
            values.configCarouselUri = this.state.configCarouselUri
        } else {
            values.configCarouselUri = values.configCarouselUri.trim()
        }
        let str = ''
        if (values.users && values.users.length !== 0) {
            values.users.map((item, index) => {
                str += item.key + '=' + item.value
                if (index + 1 !== values.users.length) {
                    str += '&'
                }
            })
            values.configCarouselUri = values.configCarouselUri.trim() + '?' + str
            delete values.users
        } else {
            values.configCarouselUri = values.configCarouselUri.trim()
        }
        // 处理展示时间
        if (values.time.length > 0) {
            values.startTime = values.time[0].format('YYYY-MM-DD HH:mm:ss');
            values.endTime = values.time[1].format('YYYY-MM-DD HH:mm:ss');
            delete values.time;
        }
        if (this.state.AdID == 0) {
            // 添加
            let res = await apiAppConfigCarouselAdd({...values, configCarouselSite: 6})
            if (res.code === 0) {
                React.$message({
                    type: 'info',
                    content: '添加成功'
                })
                this.props.history.goBack()
            } else {
                this.setState({btnLoading: false})
            }
        } else {
            // 编辑
            let res = await apiAppConfigCarouselEdit({
                configCarouselId: this.state.AdID,
                ...values,
                configCarouselSite: 6
            })
            if (res.code === 0) {
                React.$message({
                    type: 'info',
                    content: '编辑成功'
                })
                this.props.history.goBack()
            } else {
                this.setState({btnLoading: false})
            }
        }
    }
    // 广告类型选择
    typeChange = e => {
        console.log(`radio checked:${e.target.value}`);
    }
    // 外链选择
    radioChange = (e) => {
        console.log(e.target)
        this.setState({
            configCarouselUri: ''
        }, () => {
            this.formRef.setFieldsValue({configCarouselUri: '', users: ''})
            const CarouselType = e.target.value
            if (CarouselType !== '1') {
                this.openMadol(CarouselType)
            } else {
                this.setState({
                    configCarouselUri: '',
                    users: ''
                })
            }
            this.setState({
                radioValue: e.target.value,
            })
        })

    }
    // 外链modal
    openMadol = (CarouselType) => {
        switch (CarouselType) {
            case '2':
                this.setState({
                    visible: true,
                    typeTitle: '商城门店'
                })
                break;
            case '3':
                this.setState({
                    visible: true,
                    typeTitle: '商城商品'
                })
                break;
            case '4':
                this.setState({
                    visible: true,
                    typeTitle: '线下门店'
                })
                break;
            case '5':
                this.setState({
                    visible: true,
                    typeTitle: '线下商品'
                })
                break;
            case '6':
                this.setState({
                    visible: true,
                    typeTitle: '服务'
                })
                break;
            case '9':
                this.setState({
                    visible: true,
                    typeTitle: '服务类目'
                })
                break;
            default:
                break;
        }
    }
    onCancel = () => {
        this.setState({
            visible: false
        })
    }

    goDetail(param) {
        let {type, typeId, typeName, storeId, storeName} = param;
        // console.log(param, 'param');
        switch (type) {
            case '2':
                const mallobj = {storeId: typeId, storeName: typeName}
                const mallCarouselUri = JSON.stringify(mallobj);
                // console.log(mallobj, mallCarouselUri)
                this.setState({
                    visible: false,
                    configCarouselUri: mallCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: typeName})
                })
                break;
            case '3':
                const goodsobj = {goodsId: typeId, goodsName: typeName, storeId: storeId, storeName: storeName}
                const goodsCarouselUri = JSON.stringify(goodsobj);
                this.setState({
                    visible: false,
                    configCarouselUri: goodsCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: `${typeName},${storeName}`})
                })
                break;
            case '4':
                const storeobj = {storeId: typeId, storeName: typeName}
                const storeCarouselUri = JSON.stringify(storeobj);
                this.setState({
                    visible: false,
                    configCarouselUri: storeCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: typeName})
                })
                break;
            case '5':
                const productobj = {productId: typeId, productName: typeName, storeId: storeId, storeName: storeName}
                const productCarouselUri = JSON.stringify(productobj);
                this.setState({
                    visible: false,
                    configCarouselUri: productCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: `${typeName},${storeName}`})
                })
                break;
            case '6':
                const serviceobj = {serviceId: typeId, serviceName: typeName, storeId: storeId, storeName: storeName}
                const serviceCarouselUri = JSON.stringify(serviceobj);
                this.setState({
                    visible: false,
                    configCarouselUri: serviceCarouselUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: `${typeName},${storeName}`})
                })
                break;
            case '9':
                const categoryobj = {serviceClassifyId: typeId, serviceClassifyName: typeName,}
                const serviceCategorylUri = JSON.stringify(categoryobj);
                this.setState({
                    visible: false,
                    configCarouselUri: serviceCategorylUri
                }, () => {
                    this.formRef.setFieldsValue({configCarouselUri: `${typeName}`})
                })
                break;
            default:
                break;
        }
    }

    // 图片上传回调
    getDetailsFileResult = value => {
        if (value && value.length) {
            let arr = value.map(v => {
                // console.log(v)
                if (v.response && v.response.code === 0) {
                    return v.response.data
                } else {
                    return v.url
                }
            }).join(',')
            this.formRef.setFieldsValue({
                configCarouselFilez: arr
            })
        }
    }
    configCarouselUriChange = (e) => {
        this.formRef.setFieldsValue({users: ''})
        this.setState({
            configCarouselUri: e
        })
    }

    getStringName(carouselUri, type) {
        let str = ''
        if (type !== '1') {
            if (carouselUri !== '') {
                // console.log(carouselUri, 'value.configCarouselUr33333i')
                carouselUri = JSON.parse(carouselUri)

                switch (type) {
                    case '2':
                        str = carouselUri.storeName
                        break;
                    case '3':
                        str = carouselUri.goodsName + carouselUri.storeName
                        break;
                    case '4':
                    case '14':
                    case '15':
                        str = carouselUri.storeName
                        break;
                    case '5':
                        str = carouselUri.productName + carouselUri.storeName
                        break;
                    case '6':
                        str = carouselUri.serviceName + carouselUri.storeName
                        break;
                    case '7':
                        str = ''
                        break;
                    case '8':
                        str = ''
                        break;
                    case '9':
                        str = carouselUri.serviceClassifyName
                        break;
                    case '10':
                        str = ''
                        break;
                    case '11':
                        str = ''
                        break;
                    case "12":
                        str = ""
                        break;
                    case "13":
                        str = ""
                        break;
                    default:
                        break;
                }
                // console.log(str, 'str')
            }
        }
        return str
    }

    render() {
        let {
            showUpFile,
            initialValues,
            visible,
            typeTitle,
            fileList,
            btnLoading,
            AdID,
            radioValue,
            fileType,
            maxSize,
            arr,
            activeList,
            configCarouselUri
        } = this.state;
        let formTailLayout = {
            labelCol: {span: 4},
            wrapperCol: {span: 5, offset: 4},
        };
        let formTailLayouts = {
            labelCol: {span: 4},
            wrapperCol: {span: 5, offset: 0},
        };
        let formItemLayout = {
            wrapperCol: {
                xs: {span: 4, offset: 0},
                sm: {span: 5, offset: 4},
            },
        };
        // console.log(configCarouselUri)
        // // fileList = [{
        // //     name: "image.png",
        // //     status: "done",
        // //     uid: "-1",
        // //     url: "https://hqmimage.oss-cn-beijing.aliyuncs.com/5042e356b6684318a8d8850d358f099c.jpg"
        // // }]
        return (
            <div className="commodity-list-detail p-layout-box">
                <GoBack history={this.props.history} title={AdID == 0 ? "新增广告" : "编辑广告"}/>
                <div className="p-layout-content">
                    <Form onFinish={this.onFinish}
                          ref={ref => this.formRef = ref}
                          labelCol={{
                              span: 4,
                          }}
                          wrapperCol={{
                              span: 6,
                          }}
                          initialValues={initialValues}
                    >
                        <Form.Item rules={[{required: true}]} label="广告名称" name="configCarouselTitle">
                            <Input/>
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="广告类型" name="configCarouselShowType">
                            <Radio.Group onChange={this.typeChange}>
                                <Radio value={0}>图片</Radio>
                                <Radio value={1} disabled>视频</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="广告素材" name="configCarouselFilez"
                                   extra={`仅限jpg,jpeg,png格式文件，大小不超过${maxSize}M`}
                        >
                            {
                                !_.isEmpty(showUpFile) &&
                                <TheUpload accept={['image/jpg', 'image/jpeg', 'image/png']} {...fileType}  maxSize={10}
                                           fileList={fileList} getFileResult={this.getDetailsFileResult}  isConversion={false} len={1}/>
                            }
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="广告时长" name="duration">
                            <InputNumber min={1} addonAfter="秒"/>
                        </Form.Item>
                        {/*<Form.Item rules={[{required: true}]} label="是否支持跳过" name="pass">*/}
                        {/*    <Radio.Group>*/}
                        {/*        <Radio value="1">是</Radio>*/}
                        {/*        <Radio value="0">否</Radio>*/}
                        {/*    </Radio.Group>*/}
                        {/*</Form.Item>*/}
                        {/*<Form.Item rules={[{required: true}]} label="是否自动关闭" name="open">*/}
                        {/*    <Radio.Group>*/}
                        {/*        <Radio value="1">是</Radio>*/}
                        {/*        <Radio value="0">否</Radio>*/}
                        {/*    </Radio.Group>*/}
                        {/*</Form.Item>*/}
                        <Form.Item label="外链" name="configCarouselType">
                            <Radio.Group onChange={this.radioChange} initialValue={radioValue} buttonStyle="solid">
                                <Radio.Button onClick={this.radioChange} value={'1'}>地址链接</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'2'}>商城门店</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'3'}>商城商品</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'4'}>线下门店</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'5'}>线下商品</Radio.Button>
                                {/* <Radio.Button onClick={this.radioChange} value={'6'}>服务</Radio.Button> */}
                                <Radio.Button onClick={this.radioChange} value={'7'}>邀请有礼</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'8'}>砍一刀</Radio.Button>
                                {/* <Radio.Button onClick={this.radioChange} value={'9'}>服务列表</Radio.Button> */}
                                <Radio.Button onClick={this.radioChange} value={'10'}>我的卡包</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'11'}>宠物出行</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'20'}>领券中心</Radio.Button>
                                <Radio.Button onClick={this.radioChange} value={'27'}>签到积分</Radio.Button>
                            </Radio.Group>
                        </Form.Item>
                        {radioValue === '0' ? <Form.Item name={'configCarouselUri'} {...formTailLayout}>
                                <Input readOnly placeholder="需选择外链类型"/>
                            </Form.Item> :
                            radioValue === '1' ?
                                <Form.Item label="选择链接"  {...formTailLayouts} name={'configCarouselUri'}>
                                    <Select placeholder="请选择外链网址" onChange={this.configCarouselUriChange}>
                                        {
                                            activeList.map(item => <Option value={item.activityLink}
                                                                           key={item.id}>{item.activityName}</Option>)
                                        }

                                    </Select>
                                </Form.Item> :
                                (radioValue === '7' || radioValue === '8' || radioValue === "10" || radioValue === "11" || radioValue === "12" || radioValue === "20" || radioValue === "27") ?
                                    <Form.Item name={'configCarouselUri'}
                                               {...formTailLayout}>
                                        <Input readOnly placeholder="无需填写"/>
                                    </Form.Item> :
                                    <Form.Item rules={[{required: true, message: '请选择链接内容'}]}
                                               name={'configCarouselUri'}
                                               {...formTailLayout}>
                                        {/*<Input readOnly/>*/}
                                        <div style={{border:'1px solid #ccc',lineHeight:'28px',paddingLeft:'10px',minHeight:'30px' }}>
                                            {
                                                this.getStringName(configCarouselUri, radioValue)
                                            }
                                        </div>
                                    </Form.Item>
                        }
                        {
                            radioValue === '1' && configCarouselUri !== '' ? <Form.List name="users" initialValue={arr}>
                                {(fields, {add, remove}) => (
                                    <>
                                        <Form.Item label="参数">
                                            <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined/>}>
                                                添加参数
                                            </Button>
                                        </Form.Item>
                                        {fields.map(({key, name, ...restField}) => (
                                            <Form.Item
                                                {...formItemLayout}
                                                required={false}
                                                key={key}
                                                style={{
                                                    margin: 0
                                                }}
                                            >
                                                <Space
                                                    style={{
                                                        display: 'flex',
                                                        marginBottom: 0,
                                                    }}
                                                    align="baseline"
                                                >
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'key']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: '请输入参数名',
                                                            },
                                                        ]}

                                                    >
                                                        <Input placeholder="参数名"/>
                                                    </Form.Item>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'value']}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: '请输入参数值',
                                                            },
                                                        ]}
                                                    >
                                                        <Input placeholder="参数值"/>
                                                    </Form.Item>
                                                    <CloseCircleOutlined onClick={() => remove(name)}/>
                                                </Space>
                                            </Form.Item>
                                        ))}

                                    </>
                                )}
                            </Form.List> : ''
                        }
                        <Modal
                            visible={visible}
                            onCancel={this.onCancel}
                            title={typeTitle}
                            width='1000px'
                            destroyOnClose={true}
                            footer={null}
                        >
                            <List radiotype={radioValue} getList={(e) => this.goDetail(e)}/>
                        </Modal>
                        <Form.Item rules={[{required: true}]} label="展示时间" name="time">
                            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
                        </Form.Item>
                        <Form.Item rules={[{required: true}]} label="排序" name="configCarouselSort">
                            <InputNumber min={0} placeholder="*App展示顺序由小到大"/>
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                offset: 4,
                                span: 16,
                            }}
                        >
                            <Space>
                                <Button onClick={() => this.props.history.goBack()}>取消</Button>
                                <Button loading={btnLoading} htmlType="submit" type="primary">保存</Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        );
    }
}

export default Edit;
